package org.korosoft.rusalad.syncnrun.cli;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.korosoft.rusalad.syncnrun.Client;
import org.korosoft.rusalad.syncnrun.command.SyncRemoteDirCmd;

import java.io.File;

/**
 * Download files from remote server command
 *
 * @author Dmitry Korotkov
 * @since 1.0
 */
public class CliRetrieve extends CliClientCommand {
    private static final Log log = LogFactory.getLog(CliRetrieve.class);

    public CliRetrieve() {
        super("retrieve", "Retrieve files from remote server");
        options.addOption(OptionBuilder.withLongOpt("source").withDescription("Remote file or directory").hasArg().isRequired().create("s"));
        options.addOption(OptionBuilder.withLongOpt("target").withDescription("Local target directory").hasArg().isRequired().create("t"));
        addCommonLoggingOpts();
    }

    @Override
    protected int doExecute(Client client, CommandLine commandLine) throws Exception {
        String source = commandLine.getOptionValue("source");
        String target = commandLine.getOptionValue("target");

        long startTime = System.currentTimeMillis();
        SyncRemoteDirCmd.SyncRemoteDirAnswer syncRemoteDirAnswer = client.execCommandSynchronously(new SyncRemoteDirCmd(new File(target), source));
        long duration = System.currentTimeMillis() - startTime;

        log.info(String.format("Retrieved %d bytes in %d second at rate %f MB/s", syncRemoteDirAnswer.bytesSent, duration / 1000, syncRemoteDirAnswer.bytesSent * 1.0 / (duration * 1000.0)));

        return 0;
    }
}
